﻿(function promiseExamples(main) {
    "use strict";

    function waitFor(ms) {
        return new WinJS.Promise(function (success, error, progress) {
            try {
                setTimeout(function (e) {
                    try {
                        success(ms);
                    }
                    catch (ex) {
                        error(ex);
                    }
                }, ms);
            }
            catch (ex) {
                error(ex);
            }
        });
    }

    function searchTwitter(searchTerm) {
        var pr = new WinJS.Promise(function (complete, error, progress) {
            var query = "https://search.twitter.com/search.json?rpp=100&q=" + searchTerm;
            var request = new XMLHttpRequest();

            request.onprogress = function (e) {
                progress(100 * e.loaded / 85000);
            };
            request.onerror = function (e) {
                error(e);
            };
            request.onreadystatechange = function (e) {
                if (request.readyState != 4)
                    return;
                if (request.status == 200) {
                    progress(100);
                    var list = JSON.parse(request.responseText);
                    complete(list);
                }
                else {
                    error(request.responseText);
                }
            };
            request.open("get", query, true);
            request.send(null);
        });
        return pr;
    };

    main.Examples = {
        waitFor: waitFor,
        searchTwitter:searchTwitter
    };


})(this);